<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CartController extends Controller
{	
    //对商品进行遍历类别
    static public function getCate($pid){
        //定义一个空数组
        $cate=array();
        //通过传过来的pid查询类别表
        $data=DB::table('cate')->where('pid','=',$pid)->get();
        //遍历查询到的数据
        foreach($data as $k=>$v){
            //通过自身的id去掉用自身的方法(通过pid查询) 判断下面是否还存在子分类 如果有就把他压入自身的一个下标中
            $v['fenlei']=self::getCate($v['cid']);
            //将每次得到的数据遍历到空数组中
            $cate[]=$v;
        } 
         return $cate;
    } 

	/*购物车列表*/
    public function getShow() {
    	// 判断是否已登录
        $cate = self::getCate(0);
    	if(!empty(session('h_user'))){
            $h_uid = session('h_user')['h_uid'];
            $date = DB::table('cart') ->join('goods','cart.gid','=','goods.gid') -> where('h_uid',$h_uid) -> get();
            
            // 计算总价
            $total = 0;
            foreach($date as $k => $v){
                $total += ($v['gprice'] * $v['cnt']);
            }
             return view('/home/cart/cart',['date'=>$date,'total'=>$total,'cate'=>$cate]);
        }else{
            // 否则跳转登录页
            return redirect('home/index/index');
        }
    }

    /*在商品详情页添加到购物车*/
    public function postAdd(Request $request) {
        // 判断是否登录-----
        if(empty(session('h_user'))){
            // 跳转登录页面
            return redirect('/home/login/index');
        }else{
            // 获取数据,跳转加入购物车成功页面
            $date = $request -> only(['gid','cnt']);
            
            // 如果要加入购物车的商品数量为0及以下,则返回
            if($date['cnt']<=0){
                return back() -> with('error','无法接受0件及以下商品');
            }
            
            // 获得h_uid
            $date['h_uid'] = session('h_user')['h_uid'];
            
            // 加入购物车成功,更新购物车表,首先判断购物车中是否已有本商品
            $test = DB::table('cart') -> where('h_uid',$date['h_uid']) -> where('gid',$date['gid']) -> first();
            
            // 如果没有本商品,则执行插入操作,如果有本商品,则执行更新变更数量操作
            if(empty($test)){
                $res = DB::table('cart') -> insert($date);
                if($res){
                    $request -> flash();
                    return redirect('/home/cart/addsuc');
                }
            }else{
                $res = DB::table('cart') -> where('carid',$test['carid']) -> update(['cnt' => ($date['cnt']+$test['cnt'])]);
                if($res){
                    $request -> flash();
                    return redirect('/home/cart/addsuc');
                }
            }
            // 如果更新购物车表不成功则返回上一页
            return back();
        }    	
    }

    /*在商品列表页添加到购物车*/
    public function getAddadd(Request $request){
        // 判断是否登录-----
        if(empty(session('h_user'))){
            // 跳转登录页面
            return redirect('/home/login/index');
        }else{
            // 获取数据,跳转加入购物车成功页面
            $date = $request -> only(['gid','cnt']);            
            $date['h_uid'] = session('h_user')['h_uid'];

            // 加入购物车成功,更新购物车表,首先判断购物车中是否已有本商品
            $test = DB::table('cart') -> where('h_uid',$date['h_uid']) -> where('gid',$date['gid']) -> first();
            
            // 如果没有本商品,则执行插入操作,如果有本商品,则执行更新变更数量操作
            if(empty($test)){
                $res = DB::table('cart') -> insert($date);
                if($res){
                    $request -> flash();
                    return redirect('/home/cart/addsuc');
                }
            }else{
                $res = DB::table('cart') -> where('carid',$test['carid']) -> update(['cnt' => ($date['cnt']+$test['cnt'])]);
                if($res){
                    $request -> flash();
                    return redirect('/home/cart/addsuc');
                }
            }
            // 如果更新购物车表不成功则返回上一页
            return back();
        }
    }

    /*加入购物车成功*/
    public function getAddsuc(Request $request) {
        $cate = self::getCate(0);

        // 获得闪存中的数据
        $old = old();

        // 如果闪存中有数据,则查询商品表,显示加入购物车成功
        if(!empty($old)) {
            $date = DB::table('goods') -> where('gid',$old['gid']) -> select('gid','gname','gpic','gdesc','gprice') -> first();
            $date['cnt'] = $old['cnt'];
            return view('/home/cart/cartSuccess',['date'=>$date,'cate'=>$cate]);
        }else{
            // 如果闪存中没有数据,则返回上一页
            return back();
        }      
    }

    /*从购物车删除*/
    public function getDelete(Request $request) {
    	$id = $request-> input('id');
    	$res = DB::table('cart') -> where('carid',$id) -> delete();
    	if($res > 0){
            // 提示删除失败  跳转购物车页
    		return redirect('/home/cart/show') -> with('error','删除商品失败');
    	}else{
    		// 提示删除失败  跳转购物车页
            return redirect('/home/cart/show') -> with('success','删除商品成功');
    	}
    }

    /*ajax购物车删除*/
    public function postAdelete(Request $request){
        // 获得carid购物车id
        $id = $request -> input('id');

        // 删除carid匹配的数据
        DB::table('cart') -> where('carid',$id) -> delete();

        // 计算剩余cart中的数据的总价格和剩余数量
        $date = DB::table('cart') -> join('goods','cart.gid','=','goods.gid') -> where('h_uid',session('h_user')['h_uid']) -> get();
        $total = 0;
        $cnt = 0;
        foreach($date as $k => $v){
            $total += $v['gprice'] * $v['cnt'];
            $cnt += 1;
        }
        $res['total'] = $total;
        $res['cnt'] = $cnt;

        // 返回json数据
        $res = json_encode($res);
        echo $res;
    }    

    /*确认订单1*/
    public function postCc1(Request $request) {
        $request -> flash();
        return redirect('/home/cart/cc2');        
    }

    /*确认订单2*/
    public function getCc2() {
        $cate = self::getCate(0);
        // 返回的旧数据,用于查找       
        if(!empty(old())){
            session(['oldold'=>old()]);
        }        
        $date1 = session('oldold');
        // 拼接的二维数组的内层数组
        $date2 = [];
        // 拼接的二维数组的外围数组
        $date = [];
        // 去掉_token
        unset($date1['_token']);
        // 获得登录的uid
        $h_uid = session('h_user')['h_uid'];
        // dd($h_uid);

        // 所有订单的总金额
        $total = 0;
        foreach($date1 as $k => $v){
            // 删除购物车表内容
            DB::table('cart') -> where('h_uid',$h_uid) -> where('gid',$k) -> delete();
            // 拼接二维数组
            $date2 = DB::table('goods') -> where('gid',$k) -> first();
            $date2['cnt'] = $v;
            array_push($date,$date2);
            $total += $date2['gprice']*$date2['cnt'];
            $date2 = [];
        }
        session(['order'=>$date]);
        
        // 获得地址内容
        $addr = DB::table('address') -> where('h_uid',$h_uid) -> get();

        // 获得默认地址内容 如果有默认则用默认,如果没有默认用第一条地址
        $defu = DB::table('address') -> where('h_uid',$h_uid) -> where('defu',1) -> first();  
        if(empty($defu)){
            $defu = DB::table('address') -> where('h_uid',$h_uid) -> first();
        }

        return view('/home/cart/confirm',['date'=>$date,'total'=>$total,'cate'=>$cate,'addr'=>$addr,'defu'=>$defu]);        
    }


    /*下单成功*/
    public function postOo1(Request $request) {

        // 获得传入的收件人信息
        $aid = $request -> input('aid');
        $date = $request -> except('_token','aid');
        
        // 更新地址表,判断是否是新地址,如果是老地址则进行更新,如果是新地址则添加
        $addrdate = $date;
        unset($addrdate['umsg']);
        unset($addrdate['oprice']);
        $addrdate['h_uid'] = session('h_user')['h_uid'];
        if($aid==0){
            DB::table('address') -> insert($addrdate);
        }else{
            DB::table('address') -> where('aid',$aid) -> update($addrdate);
        }        
        
        // 将省市区整合到地址中
        $date['addr'] = $date['province'].$date['city'].$date['area'].$date['addr'];
        // 将收件人信息传入session        
        session(['receive'=>$date]);

        // 初始化order的值
        $order = [];        
        $order['oprice'] = 0;
        foreach(session('order') as $k => $v){
            $order['oprice'] += $v['gprice']*$v['cnt'];
            //更新商品表 更新售出与库存
            DB::table('goods') -> where('gid',$v['gid']) -> decrement('gcount',$v['cnt']);
            DB::table('goods') -> where('gid',$v['gid']) -> increment('gsold',$v['cnt']);
        }
        
        $order['h_uid'] = session('h_user')['h_uid'];        
        $order['ostatus'] = 0; // 0是未发货 1是已发货未收货 2是确认收货
        $order['otime'] = time();
        $order['rec'] = $date['rec'];
        $order['addr'] = $date['addr'];
        $order['tel'] = $date['tel'];
        $order['umsg'] = $date['umsg'];

        // 更新order表,插入新的数据
        $oid = DB::table('order') -> insertGetId($order);

        // 更新用户表 积分与消费总额
        DB::table('home_user') -> where('h_uid',session('h_user')['h_uid']) -> increment('h_utotal',$order['oprice']);
        DB::table('home_user') -> where('h_uid',session('h_user')['h_uid']) -> increment('h_ujifen',$order['oprice']*7);

        // 订单详情表的内容
        $order_detail = [];
        foreach(session('order') as $k => $v){
            $order_detail['oid'] = $oid;
            $order_detail['gid'] = $v['gid'];
            $order_detail['gprice'] = $v['gprice'];
            $order_detail['gnum'] = $v['cnt'];
            $order_detail['h_uid'] = $order['h_uid'];
            DB::table('order_detail') -> insert($order_detail);
            $order_detail = [];
        }

        // 订单完成的信息
        $cartover['oid'] = $oid;
        $cartover['oprice'] = $date['oprice'];
        $cartover['rec'] = $date['rec'];
        $cartover['addr'] = $date['addr'];
        $cartover['tel'] = $date['tel'];
        $cartover['umsg'] = $date['umsg'];

        // 写入session
        session(['cartover'=>$cartover]);
        
        return redirect('/home/cart/oo2');
    }

    /*显示完成的订单信息*/
    public function getOo2() {
        $cate = self::getCate(0);
        return view('/home/cart/overCart',['cate'=>$cate]);
    }
   
}
